package com.suxin.spring.linked;

import org.springframework.web.context.WebApplicationContext;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;

/**
 * @author Tang
 * @classname DelegatingFilterProxy
 * @description [ 包装到容器里面 ]
 * @date 2022/8/29 10:27
 */
public class DelegatingFilterProxy implements Filter {

    private Filter delegate;
    private String targetName;
    private WebApplicationContext applicationContext;

    public DelegatingFilterProxy(String targetName) {
        this(null, targetName);
    }

    public DelegatingFilterProxy(Filter delegate, String targetName) {
        this(null, targetName,null);
    }

    public DelegatingFilterProxy(Filter delegate, String targetName, WebApplicationContext applicationContext) {
        this.delegate = delegate;
        this.targetName = targetName;
        this.applicationContext = applicationContext;
    }

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response,
                         FilterChain filterChain) {
        if (this.delegate == null) {
            // 从容器中初始化代理filter
            this.delegate = initDelegate();
        }
        this.delegate.doFilter(request, response, filterChain);
    }

    private Filter initDelegate() {
        if (this.applicationContext != null) {
            if (this.delegate == null) {
                return this.applicationContext.getBean(this.targetName, Filter.class);
            }
        }
        return this.delegate;
    }

    public void setApplicationContext(@NotNull WebApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }
}